package com.example.texted.aspectj;


import com.google.common.collect.Maps;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class MyAspect {
    //    @Before("@annotation(com.example.texted.aspectj.CheckToken)")
    @Before("@within(com.example.texted.aspectj.CheckToken)||@annotation(com.example.texted.aspectj.CheckToken)")
    public void before(JoinPoint joinPoint) {
        if (joinPoint == null) {
            System.out.println("joinPoint is null");
            return;
        }
        System.out.println("joinPoint get");
        Object[] args = joinPoint.getArgs();
        System.out.println("args:  " + Arrays.toString(args));

        //获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        //从获取RequestAttributes中获取HttpServletRequest的信息
        if (null == requestAttributes) {
            System.out.println("requestAttributes is null");
            return;
        }
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        //如果要获取Session信息的话，可以这样写：
        //HttpSession session = (HttpSession) requestAttributes.resolveReference(RequestAttributes.REFERENCE_SESSION);
        //获取请求参数
        if (null == request) {
            System.out.println("request is null");
            return;
        }
        Enumeration<String> enumeration = request.getParameterNames();
        String token = request.getHeader("token");
        System.out.println("head token:  " + token);
        HashMap<String, String> requestMap = new HashMap<>();
        requestMap.put("token", token);

        //请求接口 验证token

        Map<String, String> parameterMap = Maps.newHashMap();
        while (enumeration.hasMoreElements()) {
            String parameter = enumeration.nextElement();
            parameterMap.put(parameter, request.getParameter(parameter));
        }
        System.out.print("parameterMap:  ");
        System.out.println(parameterMap);
//        String str = JSON.toJSONString(parameterMap);
//        if(obj.length > 0) {
//            logger.info("请求的参数信息为："+str);
//        }
    }
}
